#!/bin/bash

setup_ttys()
{
    for i in 1 2 3 4 5 6; do
        if [ -e /dev/tty${i} ]; then
            echo 'tty'$i'::respawn:/sbin/getty 38400 tty'$i >> /etc/inittab
            echo tty$i >> /etc/securetty
        fi
    done

    for x in $(cat /proc/cmdline); do
    case $x in
        rescue)
            MODE=shell
            ;;
        console=*)
            CONSOLE_SPEC=${x#console=}
            IFS=, read TTY BAUDRATE _ <<<"${CONSOLE_SPEC},9600"
            if [ -e /dev/${TTY} ] && ! grep -q "^${TTY}::" /etc/inittab; then
                echo "${TTY}::respawn:/sbin/getty -L ${BAUDRATE} ${TTY} vt100" >> /etc/inittab
                echo ${TTY} >> /etc/securetty
            fi
            ;;
        esac
    done
}

setup_sudoers()
{
    echo '%sudo   ALL = (ALL) ALL' > /etc/sudoers.d/sudo
    echo 'rancher ALL = (ALL) NOPASSWD: ALL' >> /etc/sudoers.d/sudo
}

setup_services()
{
    for i in hwdrivers dmesg devfs loadkmap udev udev-root udev-coldplug; do
        ln -s /etc/init.d/$i /etc/runlevels/sysinit
    done

    for i in acpid hwclock syslog bootmisc hostname sysctl modules connman dbus haveged issue; do
        ln -s /etc/init.d/$i /etc/runlevels/boot
    done

    for i in sshd "local" ccapply iscsid; do
        ln -s /etc/init.d/$i /etc/runlevels/default
    done

    for i in savecache killprocs mount-ro; do
        ln -s /etc/init.d/$i /etc/runlevels/shutdown
    done

    for what in unknown $(virt-what || true); do
        case $what in
            kvm|qemu)
                ln -s /etc/init.d/qemu-guest-agent /etc/runlevels/boot/
                ;;
            microsoft|hyperv)
                ln -s /etc/init.d/hv_kvp_daemon /etc/runlevels/boot/
                ln -s /etc/init.d/hv_fcopy_daemon /etc/runlevels/boot/
                ln -s /etc/init.d/hv_vss_daemon /etc/runlevels/boot/
                ;;
            vmw|vmware)
                ln -s /etc/init.d/open-vm-tools /etc/runlevels/boot/
                ;;
        esac
    done
}

setup_config()
{
    k3os config --boot
    if [ -e /etc/conf.d/udev-settle ]; then
        ln -s /etc/init.d/udev-settle /etc/runlevels/sysinit/
    fi
    if [ -e /var/lib/connman/cloud-config.config ]; then
        echo 'rc_want="wpa_supplicant"' >> /etc/conf.d/connman
    fi
    if [ -e /etc/conf.d/cloud-config ]; then
        ln -s /etc/init.d/cloud-config /etc/runlevels/boot/
    fi
    if [ -e /etc/conf.d/rngd ]; then
        ln -s /etc/init.d/rngd /etc/runlevels/boot/
    fi
}

setup_root()
{
    if [ ! -e /root ]; then
        mkdir -p /root
        chmod 0700 /root
    fi
}

setup_hosts()
{
    if [ -e /etc/hosts ]; then
        return 0
    fi

    HOSTNAME=$(</etc/hostname)
    cat > /etc/hosts << EOF
127.0.0.1	localhost localhost.localdomain
127.0.1.1	${HOSTNAME} ${HOSTNAME}.localdomain

::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
EOF
}

setup_hostname()
{
    if [ -e /etc/hostname ]; then
        return 0
    fi

    if [ -e /var/lib/rancher/k3os/hostname ]; then
        cp /var/lib/rancher/k3os/hostname /etc/hostname
        return 0
    fi

    mkdir -p /var/lib/rancher/k3os
    HOSTNAME=k3os-${RANDOM}
    echo $HOSTNAME > /var/lib/rancher/k3os/hostname
    cp /var/lib/rancher/k3os/hostname /etc/hostname

}

setup_mounts()
{
    if [ -d /.base/boot ]; then
        mkdir -p /boot
        mount --bind /.base/boot /boot
    fi

    if [ -e /.base/k3os/system ]; then
        mkdir -p /k3os/system
        mount -o ro --bind /.base/k3os/system /k3os/system
    fi

    # Twice on purpose.  A live system double mounts this
    while mountpoint -q /.base; do
        umount -l /.base
    done
}

setup_manifests()
{
    mkdir -p /var/lib/rancher/k3s/server/manifests
    rsync -a --exclude='*.example' /usr/share/rancher/k3s/server/manifests/ /var/lib/rancher/k3s/server/manifests/
}

setup_state_dirs()
{
    mkdir -p /var/lib/nfs
    mkdir -p /var/lib/rancher/k3s/agent/libexec/kubernetes
}

do_grow_live()
{
    parted $1 resizepart $2 yes 100%
    partprobe $1
    sleep 2
    resize2fs $3
}

grow_live()
{
    if [ "$K3OS_MODE" != "local" ]; then
        return 0
    fi

    if [ -e /k3os/system/growpart ]; then
        read DEV NUM < /k3os/system/growpart
        if [ ! -e "${DEV}${NUM}" ]; then
            # /dev/sda2 => /dev/sda2
            # /dev/nvme0n1p2 => /dev/nvme0n1p2
            PART=$(blkid -L K3OS_STATE)

            # /dev/sda2 => /dev/sda
            # /dev/nvme0n1p2 => /dev/nvme0n1
            DEV=$(echo "$PART" | sed -r 's/((\d+)p)?\d+$/\2/')

            # /dev/sda2 => 2
            # /dev/nvme0n1p2 => 2
            NUM=$(echo "$PART" | sed 's!.*[^0-9]!!')
        fi
        pinfo Growing ${PART:=${DEV}${NUM}}
        do_grow_live $DEV $NUM $PART || true
        rm -f /k3os/system/growpart
    fi
}

setup_mounts
grow_live
setup_hostname
setup_hosts
setup_root
setup_ttys
setup_sudoers
setup_services
setup_config
setup_manifests
setup_state_dirs
cleanup
